parameters:
  - name: VSCODE_QUALITY
    type: string

steps:
  - task: NodeTool@0
    inputs:
      versionSource: fromFile
      versionFilePath: .nvmrc
      nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download

  - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}:
    - template: ./distro/download-distro.yml@self

    - task: AzureKeyVault@1
      displayName: "Azure Key Vault: Get Secrets"
      inputs:
        azureSubscription: "vscode-builds-subscription"
        KeyVaultName: vscode-build-secrets
        SecretsFilter: "github-distro-mixin-password"

  - script: node build/setup-npm-registry.js $NPM_REGISTRY
    condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none'))
    displayName: Setup NPM Registry

  - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.js compile > .build/yarnlockhash
    displayName: Prepare node_modules cache key

  - task: Cache@2
    inputs:
      key: '"node_modules" | .build/yarnlockhash'
      path: .build/node_modules_cache
      cacheHitVar: NODE_MODULES_RESTORED
    displayName: Restore node_modules cache

  - script: tar -xzf .build/node_modules_cache/cache.tgz
    condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true'))
    displayName: Extract node_modules cache

  - script: |
      set -e
      npm config set registry "$NPM_REGISTRY" --location=project
      # npm >v7 deprecated the `always-auth` config option, refs npm/cli@72a7eeb
      # following is a workaround for yarn to send authorization header
      # for GET requests to the registry.
      echo "always-auth=true" >> .npmrc
      yarn config set registry "$NPM_REGISTRY"
    condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none'))
    displayName: Setup NPM & Yarn

  - task: npmAuthenticate@0
    inputs:
      workingFile: .npmrc
    condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none'))
    displayName: Setup NPM Authentication

  - script: sudo apt update -y && sudo apt install -y build-essential pkg-config libx11-dev libx11-xcb-dev libxkbfile-dev libnotify-bin libkrb5-dev
    displayName: Install build tools
    condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))

  - script: |
      set -e
      npm i -g node-gyp@9.4.0

      for i in {1..5}; do # try 5 times
        yarn --frozen-lockfile --check-files && break
        if [ $i -eq 3 ]; then
          echo "Yarn failed too many times" >&2
          exit 1
        fi
        echo "Yarn failed $i, trying again..."
      done
    env:
      ELECTRON_SKIP_BINARY_DOWNLOAD: 1
      PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
      GITHUB_TOKEN: "$(github-distro-mixin-password)"
    displayName: Install dependencies
    condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))

  - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}:
    - script: node build/azure-pipelines/distro/mixin-npm
      condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))
      displayName: Mixin distro node modules

  - script: |
      set -e
      node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt
      mkdir -p .build/node_modules_cache
      tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt
    condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'))
    displayName: Create node_modules archive

  - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}:
    - script: yarn --cwd build compile && ./.github/workflows/check-clean-git-state.sh
      displayName: Check /build/ folder

  - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}:
    - script: node build/azure-pipelines/distro/mixin-quality
      displayName: Mixin distro quality

  - template: common/install-builtin-extensions.yml@self

  - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}:
    - script: yarn npm-run-all -lp core-ci-pr extensions-ci-pr hygiene eslint valid-layers-check vscode-dts-compile-check tsec-compile-check
      env:
        GITHUB_TOKEN: "$(github-distro-mixin-password)"
        DISABLE_V8_COMPILE_CACHE: 1 # Disable v8 cache used by yarn v1.x, refs https://github.com/nodejs/node/issues/51555
      displayName: Compile & Hygiene (OSS)
  - ${{ else }}:
    - script: yarn npm-run-all -lp core-ci extensions-ci hygiene eslint valid-layers-check vscode-dts-compile-check tsec-compile-check
      env:
        GITHUB_TOKEN: "$(github-distro-mixin-password)"
        DISABLE_V8_COMPILE_CACHE: 1 # Disable v8 cache used by yarn v1.x, refs https://github.com/nodejs/node/issues/51555
      displayName: Compile & Hygiene (non-OSS)

  - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}:
    - script: |
        set -e
        yarn --cwd test/smoke compile
        yarn --cwd test/integration/browser compile
      displayName: Compile test suites (non-OSS)
      condition: and(succeeded(), eq(variables['VSCODE_STEP_ON_IT'], 'false'))

    - task: AzureCLI@2
      displayName: Fetch secrets
      inputs:
        azureSubscription: "vscode-builds-subscription"
        scriptType: pscore
        scriptLocation: inlineScript
        addSpnToEnvironment: true
        inlineScript: |
          Write-Host "##vso[task.setvariable variable=AZURE_TENANT_ID]$env:tenantId"
          Write-Host "##vso[task.setvariable variable=AZURE_CLIENT_ID]$env:servicePrincipalId"
          Write-Host "##vso[task.setvariable variable=AZURE_CLIENT_SECRET;issecret=true]$env:servicePrincipalKey"

    - script: |
        set -e
        AZURE_STORAGE_ACCOUNT="vscodeweb" \
        AZURE_TENANT_ID="$(AZURE_TENANT_ID)" \
        AZURE_CLIENT_ID="$(AZURE_CLIENT_ID)" \
        AZURE_CLIENT_SECRET="$(AZURE_CLIENT_SECRET)" \
          node build/azure-pipelines/upload-sourcemaps
      displayName: Upload sourcemaps to Azure

    - script: |
        set -e
        AZURE_STORAGE_ACCOUNT="ticino" \
        AZURE_TENANT_ID="$(AZURE_TENANT_ID)" \
        AZURE_CLIENT_ID="$(AZURE_CLIENT_ID)" \
        AZURE_CLIENT_SECRET="$(AZURE_CLIENT_SECRET)" \
          node build/azure-pipelines/upload-sourcemaps
      displayName: Upload sourcemaps to Azure (Deprecated)

    - script: ./build/azure-pipelines/common/extract-telemetry.sh
      displayName: Generate lists of telemetry events

    - script: tar -cz --ignore-failed-read --exclude='.build/node_modules_cache' --exclude='.build/node_modules_list.txt' --exclude='.build/distro' -f $(Build.ArtifactStagingDirectory)/compilation.tar.gz .build out-* test/integration/browser/out test/smoke/out test/automation/out
      displayName: Compress compilation artifact

    - task: 1ES.PublishPipelineArtifact@1
      inputs:
        targetPath: $(Build.ArtifactStagingDirectory)/compilation.tar.gz
        artifactName: Compilation
        sbomEnabled: false
      displayName: Publish compilation artifact

    - script: yarn download-builtin-extensions-cg
      env:
        GITHUB_TOKEN: "$(github-distro-mixin-password)"
      displayName: Download component details of built-in extensions

    - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
      displayName: "Component Detection"
      inputs:
        sourceScanPath: $(Build.SourcesDirectory)
        alertWarningLevel: Medium
      continueOnError: true
